package ChatSystem;

import java.util.ArrayList;

/**
 * A specialized Sender which sends ChatFileMessages over a TCPSender.
 * It stores messages until they are accepted or denied by the remote ChatSystem, and then enqueues them to be actually sent.
 */
public class FileSender extends Sender<ChatMessage.ChatFileMessage, TCPSender> {
	protected final ArrayList<ChatMessage.ChatFileMessage> _pendingMessages;
	/**
	 * Creates the sender.
	 */
	public FileSender() {
		super(new TCPSender());
		_pendingMessages = new ArrayList<ChatMessage.ChatFileMessage>();
	}
	
	@Override
	protected void cancel() {
		_sender.cancel();
	}

	@Override
	public void postMessage(ChatMessage.ChatFileMessage message) {
		_pendingMessages.add(message);
	}
	
	/**
	 * Notifies that the message has been accepted and put the file in the sending queue.
	 * @param fileRecipient The remote user
	 * @param filename The name of the file to be sent
	 * @throws IllegalArgumentException when the message does not exist.
	 */
	public void acceptMessage(User fileRecipient, String filename) throws IllegalArgumentException {
		ChatMessage.ChatFileMessage message = this.findMessage(fileRecipient, filename);
		super.postMessage(message);
		_pendingMessages.remove(message);
	}

	/**
	 * Notifies that the message has been denied and discard the file.
	 * @param fileRecipient The remote user
	 * @param filename The name of the file to be sent
	 * @throws IllegalArgumentException when the message does not exist.
	 */
	public void declineMessage(User fileRecipient, String filename) throws IllegalArgumentException {
		ChatMessage.ChatFileMessage message = this.findMessage(fileRecipient, filename);
		_pendingMessages.remove(message);
		message.setState(ChatMessage.ChatFileMessage.State.Declined);
	}
	
	/**
	 * Find a pending message using the provided arguments.
	 * @param fileRecipient The remote user
	 * @param filename The name of the file to be sent
	 * @return The pending message.
	 * @throws IllegalArgumentException when the message does not exist.
	 */
	private ChatMessage.ChatFileMessage findMessage(User fileRecipient, String filename) throws IllegalArgumentException {
		for(ChatMessage.ChatFileMessage msg : _pendingMessages) {
			if(msg.getRecipient().equals(fileRecipient) && msg.getFilename().equals(filename)) {
				return msg;
			}
		}
		
		throw new IllegalArgumentException();
	}

	@Override
	protected void sendMessage(ChatMessage.ChatFileMessage message) {
		_sender.sendMessage(message);
	}
}
